package com.example.chat_demo.controller.http;

import com.example.chat_demo.controller.ws.WebSocketServer;
import com.example.chat_demo.data.UserData;
import com.example.chat_demo.entry.Message;
import com.example.chat_demo.entry.Result;
import com.example.chat_demo.entry.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@CrossOrigin
public class MessageController {


    @Resource
    private  WebSocketServer webSocketServer;

    @PostMapping("sendMessage")
    public String receiveMessage(@RequestBody  Message message){
        ObjectMapper objectMapper = new ObjectMapper();
        String s ="";
        try {
            s=objectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        this.webSocketServer.sendInfo(message.getReceive_uid(),s);
       return "ok";
    }

    @GetMapping("/login")
    public Result<User> login( String userId){

        System.out.println(userId);
        if ( UserData.isLogin(userId)){
            return new Result<User>(400,null,"用户已经登陆");
        }else {
            User user = UserData.creatUser(userId);
            System.out.println(user);
            return new Result<User>(200,user,"登陆成功");
        }


    }







}
